from __future__ import print_function
from twisted.internet.protocol import Factory
from twisted.internet import reactor,protocol
import os
os.chdir(os.path.dirname(os.path.abspath(__file__)))


class PyServer(protocol.Protocol):
    def __init__(self,user):
        self.user = user
        self.state = 1
    def connectionMade(self):
        host = self.transport.getPeer().host
        print("There are new connections %s" % host)

        if host == "127.0.0.1":
            if self.getPyClientNumber() >0:
                clinet = self.user.pyClientUsers.pop()
                self.user.bindUsers[self] = clinet
                self.user.bindUsers[clinet] = self

            else:
                print("If there are no redundant Python clients, close the mstsc client")
                del self
        else:
            print("The user mark is not authenticated as 0")
            self.state = "0"

    def connectionLost(self, reason):
        print(("bengin close client",self.user.pyClientUsers,self.user.bindUsers))
        if self in self.user.bindUsers:
            del self.user.bindUsers[self]

        if self in self.user.pyClientUsers:
            self.user.pyClientUsers.remove(self)
        print(("end close client", self.user.pyClientUsers, self.user.bindUsers))

    def dataReceived(self, data):
        if self.state == "0":
            if data == token:
                self.transport.write("1")
                self.state = "1"
                self.user.pyClientUsers.append(self)
            else:
                self.transport.write("0")
                del self
        else:
            self.user.bindUsers[self].transport.write(data)


    def getPyClientNumber(self):
        return len(self.user.pyClientUsers)


class PyServerFactory(Factory):
    def __init__(self):
        self.pyClientUsers=[]
        self.bindUsers={}
    def buildProtocol(self, addr):
        return PyServer(self)


if __name__ == '__main__':
    listenPort = 9999
    token = "XhYno123456789"

    reactor.listenTCP(listenPort,PyServerFactory())
    reactor.run()